package command.receiver;

import java.io.BufferedWriter;
import java.io.IOException;
//import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import pojo.OnlineSocket;
import pojo.Protocol;
import util.ProtocolJSONConverter;
import command.BaseReceiver;

public class SendToOneUserReceiver extends BaseReceiver {

	public SendToOneUserReceiver(Map<String, OnlineSocket> connectedUsers,
			Protocol protocol) {
		super(connectedUsers, protocol);
	}

	@Override
	public Entry<Integer, List<Object>> action() throws IOException {
		List<Object> offlineUsers = new ArrayList<>();
		String sendTo = protocol.getTo();
		
		OnlineSocket msgReceiver = connectedUsers.get(sendTo);
		
		if (msgReceiver == null) {
			return null;
		}
		
		try {
//			ObjectOutputStream objOut = new ObjectOutputStream(msgReceiverOut);
//			objOut.writeObject(protocol);
			
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(msgReceiver.getOutputStream()));
			writer.write(ProtocolJSONConverter.toJSON(protocol) + "\n");
			writer.flush();
		} catch (SocketException e) {
			connectedUsers.remove(sendTo);
			offlineUsers.add(sendTo);
		}

		if (offlineUsers.isEmpty()) {
			return null;
		}
		
		return new AbstractMap.SimpleEntry<Integer, List<Object>>(BaseReceiver.USER_OFFLINE, offlineUsers);
	}

}
